package cn.xiuxius.embedded.util;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

public class CharsetUtil {

    public static Charset detectCharset(Path path) throws IOException {
        byte[] buf = Files.readAllBytes(path);

        // Step 1: 用 UniversalDetector 探测
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(buf, 0, buf.length);
        detector.dataEnd();

        String detectedEncoding = detector.getDetectedCharset();
        Charset detectedCharset = null;

        if (detectedEncoding != null) {
            try {
                detectedCharset = Charset.forName(detectedEncoding);

                // 验证这个编码能否正确解码整个文件
                new String(buf, detectedCharset); // 如果失败，会抛异常
                return detectedCharset;
            } catch (Exception ignored) {

            }
        }

        // Step 2: 备选编码尝试（如果探测失败或解码失败）
        List<Charset> fallbackCharsets = Arrays.asList(
                StandardCharsets.UTF_8,
                Charset.forName("GBK"),
                StandardCharsets.ISO_8859_1
        );

        for (Charset charset : fallbackCharsets) {
            try {
                new String(buf, charset); // 尝试解码验证
                return charset;
            } catch (Exception ignored) {
            }
        }

        return Charset.defaultCharset();
    }

}
